﻿using System.Net.WebSockets;
using System.Text;

namespace DFGK_WMS.Common.WebSocketModule;

/// <summary>
/// WebSocketHandler 类用于处理客户端发来的消息 并保持连接状态
/// </summary>
public class WebSocketHandler
{
    private readonly WebSocketConnectManager connectionManager;

    /// <summary>
    /// 构造
    /// </summary>
    /// <param name="connectionManager"></param>
    public WebSocketHandler(WebSocketConnectManager connectionManager)
    {
        this.connectionManager = connectionManager;
    }

    /// <summary>
    /// 处理客户端发送的消息  并保持连接不中断
    /// </summary>
    /// <param name="webSocket"></param>
    /// <param name="context"></param>
    /// <returns></returns>
    public async Task Handle(WebSocket webSocket, string id)
    {
        var buffer = new byte[1024 * 4];
        // 接收客户端发送的消息
        var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
        while (!result.CloseStatus.HasValue) //result.CloseStatus 是一个可空枚举类型的属性，用于表示 WebSocket 连接的关闭状态。
        {
            // 将接收到的消息原样发送回客户端
            var receivedMessage = Encoding.UTF8.GetString(buffer, 0, result.Count);

            var sendMsgBuf = Encoding.UTF8.GetBytes(receivedMessage);
            await webSocket.SendAsync(sendMsgBuf, result.MessageType, result.EndOfMessage, CancellationToken.None);
            // 继续接收下一条消息
            result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
        }

        // 关闭 WebSocket 连接
        await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
        //移除
        connectionManager.RemoveSocket(id);
    }
}